import React from 'react'
import { connect } from 'react-redux'
import { withRouter } from 'react-router'
import { push } from 'connected-react-router'
import { projectLabelView as projectLabelViewDuck } from 'ducks'
import { Query } from 'react-apollo'
import { Layout, Flex, Fixed } from 'react-layout-pane'
import GetItem from 'graphql/getItemInfo.graphql'
import Board from './board'
import ToolBar from './toolBar'
import Loading from './loadingItem'

const pageInfo = ({
  activeItemId, isItemInit, actionReciveItemInfo, match, lableState,link,
}) => (
  <Query
    query={GetItem}
    variables={{ id: activeItemId, state: lableState === 'all' ? ['label', 'done'] : [lableState] }}
    fetchPolicy="network-only"
    onCompleted={(data) => {
      if (data.project_task_item.length > 0) {
        const item = data.project_task_item[0]
        actionReciveItemInfo({
          id: item.id,
          state: item.state,
          createTime: item.create_at,
          finishTime: item.finish_time,
          image: {
            width: item.item_object.metadata.width,
            height: item.item_object.metadata.height,
            path: `${item.item_object.dataset_object.file_server_object.address}/${
              item.item_object.real_name
            }`,
          },
          label: item.annotation_array.map(({ content, ...others }) => ({
            ...others,
            ...content,
          })),
        })
      } else {
        const url = match.url.substring(0, match.url.length - (activeItemId.length + 1))
        link(url)
      }
    }}
  >
    {({ loading, error, data }) => {
      if (loading) return <Loading />
      if (error) return `Error! ${error.message}`
      if (isItemInit !== undefined) {
        return (
          <React.Fragment>
            <Flex className="mainBoard">
              <Layout type="row">
                <Flex className="left">
                  <Board />
                </Flex>
                <Fixed className="right">
                  <ToolBar />
                </Fixed>
              </Layout>
            </Flex>
          </React.Fragment>
        )
      }
      return null
    }}
  </Query>
)

const mapStateToProps = state => ({
  activeItemId: projectLabelViewDuck.selectors.activeItemId(state),
  isItemInit: projectLabelViewDuck.selectors.isItemInit(state),
})

const mapDispatchToProps = {
  actionReciveItemInfo: projectLabelViewDuck.creators.actionReciveItemInfo,
  link: push,
}

export default withRouter(
  connect(
    mapStateToProps,
    mapDispatchToProps,
  )(pageInfo),
)
